package com.dubbo.controller;

import com.dubbo.config.DistributedLockByZookeeper;
import com.dubbo.config.RedisUtil;
import com.dubbo.pojo.Order;
import com.dubbo.pojo.User;
import com.dubbo.service.OrderService;
import com.dubbo.service.PrividerMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 *  zj: CompletableFuture __rpc 异步  事件监听拿结果：future.get()
 *
 */
@Slf4j
@Controller
@RequestMapping(value = "start")
public class RabbitmqController {


    @Reference(version="1.0.0")
    private PrividerMessageService prividerMessageService;

    @Reference(version = "1.0.0", loadbalance = "consistenthash", cluster = "failfast")
    //快速失败，只发起一次调用，失败立即报错。通常用于非幂等性的写操作，比如新增记录
    private PrividerMessageService service;

    @Resource
    private PrividerMessageService prividerMessage;
    @Resource
    private DistributedLockByZookeeper distributedLockByZookeeper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OrderService orderService;

    String PATH="lock";
    @RequestMapping(value = "rabbitmq")
    @ResponseBody
    public String RemoteUser(){
        //redis 集成
        redisUtil.setExpire("88","888",1000);
        System.out.println("===>:" + redisUtil.get("88"));
        // end
        log.info("来了");
        //分布式锁-
        distributedLockByZookeeper.acquireDistributedLock(PATH);
        User user = new User();
        user.setName("xiaomage");
        prividerMessage.consume(user);
        System.out.println(prividerMessage.consume(user));
        boolean flag = distributedLockByZookeeper.releaseDistributedLock(PATH);
        return String.valueOf(flag);
    }

    @RequestMapping(value = "/sync")
    @ResponseBody
    public String sync() throws Exception {
        User user = new User();
        user.setName("zhangsan");
        CompletableFuture<String> future = RpcContext.getContext().asyncCall(() -> {
                    return prividerMessage.consume(user);
                }
        );
        log.info("客户端异步发送：" + future.get());
        return future.get();
    }
    // OrderService
    @RequestMapping(value = "/trn")
    @ResponseBody
    public String trn() throws Exception {
        try{
            Order order=new Order();
            order.setCommodityCode("20200712");
            order.setUserId("wsypleeeeeeeee");
            order.setAmount(20.00);
            order.setCount(2);
            orderService.createOrder(order);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "ok";
    }
}
